package br;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Servlet implementation class loginm
 */
@WebServlet("/loginm")
public class loginm extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginm() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sesja = request.getSession(true);
		 response.setCharacterEncoding("UTF-8");
		 PrintWriter out = response.getWriter();
		 if(request.getParameter("ac")!=null){
			 String action = request.getParameter("ac");
			if(action.equals("log")){
				String log = request.getParameter("login");
				String pas = request.getParameter("password");
				System.out.println(log+" "+pas);
				try {
				  Connection con =mb.commons.DbConnection.getConnection 
				  ();
				  Statement stmt = con.createStatement();
				  ResultSet rs = stmt.executeQuery("SELECT * FROM uzytkownicy,kurierzy WHERE login = '"+log+"' AND haslo = '"+pas+"' AND uzytkownicy.id=kurierzy.id AND rodzaj='kurier'");
				  sesja.setAttribute("log","blad");
				  boolean blad = true;
				  while(rs.next()){
					  String l = rs.getString("login");
					  String h = rs.getString("haslo");
					  if(l.equals(log)&&h.equals(pas)){
						  blad=false;
						  sesja.setAttribute("log",rs.getString("rodzaj"));
						  sesja.setAttribute("nick",l);
						  sesja.setAttribute("idkur",rs.getInt("id_kuriera"));
						
							  response.setContentType("text/html;charset=UTF-8");
							  	System.out.println(l+"abc");
								out.println("ok;"+l);
								out.close();
					  }			  
				  
			
			
		}
				  if(blad){
					  out.println(";blad");
					  out.close();
				  }
				} catch (Exception e) {
					e.printStackTrace();
					 sesja.setAttribute("log","blad");
					 out.println(";blad");
					out.close();
				}

		}
			else if(action.equals("wyl")){
				sesja.invalidate();
				out.println("wylogowano");
				out.close();
			 }
	}
		 
	}
	}
	
